﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using ICU;
using System.IO;

namespace Chat
{
    internal class LocalMessageContainer
    {
        long _id;
        public LocalMessageContainer(long id)
        {
            _id = id;
        }
        public Message GetMessage(long id)
        {
            foreach (var item in Directory.EnumerateDirectories(Path.Combine("data",_id.ToString(),"message")))
            {
                if (Convert.ToInt64(File.ReadAllText(Path.Combine(item, "lid"))) <= id)
                {
                    bool found = false;
                    foreach (var msgf in Directory.GetFiles(item))
                    {
                        Message msg = JsonConvert.DeserializeObject<Message>(msgf);
                        if (msg.messageId == id)
                        {
                            return msg;
                        }
                    }
                    return null;
                }
            }
            return null;
        }
        public Message[] GetMessages(DateTime dateTime)
        {
            string path = Path.Combine("data", _id.ToString(), "message", dateTime.ToString("M"));
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string[] fs = Directory.GetFiles(path);
            Message[] messages = new Message[fs.Length];
            for (int i = 0; i < fs.Length; i++)
            {
                messages[i] = JsonConvert.DeserializeObject<Message>(fs[i]);
            }
            return messages;
        }
        public void AddMessage(long id,Message message)
        {
            string path = Path.Combine("data", _id.ToString(), "message", message.sendTime.ToString("M"));
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            File.WriteAllText(Path.Combine(path, id.ToString()), JsonConvert.SerializeObject(message));
            File.WriteAllText(Path.Combine(path, "lid"), id.ToString());
        }
        public static long GetLastId(long uid)
        {
            string path = Path.Combine("data", uid.ToString(), "message");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            long ret = 0;
            foreach (var item in Directory.GetDirectories(path))
            {
                long t = Convert.ToInt64(File.ReadAllText(Path.Combine(item, "lid")));
                if (t > ret)
                {
                    ret = t;
                }
            }
            return ret;
        }
    }
}
